package com.dongnao.jack.rmi.impl;

import java.lang.reflect.Method;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;

import com.alibaba.fastjson.JSONObject;
import com.dongnao.jack.invocate.bean.HttpInvocateParamBean;
import com.dongnao.jack.spring.parse.ServiceConfig;

public class SoaRemoteImpl extends UnicastRemoteObject implements SoaRemote {

    public SoaRemoteImpl() throws RemoteException {
        super();
    }

    /** 
     * @Fields serialVersionUID : 
     */
    private static final long serialVersionUID = 3997625035075973083L;

    @Override
    public String invoke(String params) throws RemoteException {

        try {

            // 使用封装执行ben
            HttpInvocateParamBean paramBean = getParamBean(params);
            if (paramBean != null) {

                ApplicationContext context = ServiceConfig.applicationContext;
                Object bean = context.getBean(paramBean.getRef());
                Method method = getMethod(bean, paramBean.getMethodName(), paramBean.getArgs());
                Object result = method.invoke(bean, paramBean.getArgs());

                return result.toString();

            }

        }
        catch (Exception e) {
            return "------error---------";
        }

        return null;
    }

    private Method getMethod(Object object, String methodName, Object[] args) {

        Method[] methods = object.getClass().getMethods();
        for (Method method : methods) {

            if (method.getName().equals(methodName)) {

                Class<?>[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length == args.length) {

                    for (int i = 0; i < args.length; i++) {
                        Object object2 = args[i];
                        if (!object2.getClass().getName().equals(parameterTypes[i].getName())) {
                            return null;
                        }
                    }

                    return method;

                }

            }

        }

        return null;
    }

    private HttpInvocateParamBean getParamBean(String params) {

        if (StringUtils.isNoneBlank(params)) {
            // JSONObject jsonObject = JSONObject.parseObject(sb.toString());
            // String object = jsonObject.get("paramInvocation").toString();
            // Object parse = JSONObject.parse(sb.toString());
            // System.out.println(parse);
            HttpInvocateParamBean bean = JSONObject.parseObject(params, HttpInvocateParamBean.class);
            // System.out.println(bean);
            // HttpInvocateParamBean parseObject = JSONObject.parseObject(parse.toString(),
            // HttpInvocateParamBean.class);
            return bean;
        }

        return null;

    }

}
